package com.hspedu.newData.dmsxl.数组.二分查找;

import org.junit.Test;

/**
 * @Author: yh
 * @description: 
 * @CreateTime: 2025-04-22 
 * @Version: 1.0
 */

public class LC34二分查找多项时查找最左和最右边 {

    public int[] searchRange(int[] nums, int target) {
        int left = searchLeft(nums, target);
        int right = searchRight(nums, target);
        return new int[]{left,right};
    }

    private int searchRight(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        int candidate = -1;
        while (left <= right){
            int mid = left + (right - left) / 2;
            if (nums[mid] > target){
                right = mid - 1;
            }else if (nums[mid] < target){
                left = mid + 1;
            }else {
                candidate = mid;
                left = mid + 1;
            }
        }
        return candidate;
    }

    private int searchLeft(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        int candidate = -1;
        while (left <= right){
            int mid = left + (right - left) / 2;
            if (nums[mid] < target){
                left = mid + 1;
            }else if (nums[mid] > target){
                right = mid - 1;
            }else {
                candidate = mid;
                right = mid - 1;
            }
        }
        return candidate;
    }

    @Test
    public void test(){
        int[] nums = new int[]{5,7,7,8,8,10};
        int[] ints = searchRange(nums, 8);
        int[] ints1 = searchRange(nums, 6);
        int[] ints2 = searchRange(nums, 0);
        System.out.println("==========");

    }
}
